/**
 * 面试题 01.05. 一次编辑
 * https://leetcode.cn/problems/one-away-lcci/
 */

/**
 * @param {string} first
 * @param {string} second
 * @return {boolean}
 */
function oneEditAway(first, second) {
  if (Math.abs(first.length - second.length) > 1) {
    return false;
  }
  const maxLength = Math.max(first.length, second.length);
  let diffIndex = 0;
  for (; diffIndex < maxLength; diffIndex += 1) {
    if (first[diffIndex] !== second[diffIndex]) {
      break;
    }
  }
  if (first.length === second.length) {
    if (diffIndex >= maxLength) {
      return true;
    }
    return first.substring(diffIndex + 1) === second.substring(diffIndex + 1);
  }
  if (diffIndex === maxLength - 1) {
    return true;
  }
  if (first.length > second.length) {
    return first.substring(diffIndex + 1) === second.substring(diffIndex);
  }
  return first.substring(diffIndex) === second.substring(diffIndex + 1);
}

console.log(oneEditAway('pale', 'ple') === true);
console.log(oneEditAway('pales', 'pal') === false);
